<?php

namespace App\Listeners;

use App\Helpers\PayTrait;
use App\Jobs\DevideAccount;
use App\Models\Map\ShopOrder;
use App\Models\Order\OrderFlow;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Http;

class DiviceAccountNotifyListener implements ShouldQueue
{
    use PayTrait;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $data = $event->order;
        info('合单解密后的对象1',$data['sub_orders']);
        $response = Http::post(env('COMMISSION_API').'/Api/paySuccess2/', $data);
        $last = $response->body();
        $result = json_decode($last,true);
        if($result){
            info('实体商品支付回调数据',$result);
        }
        // 农道回调接口
//        $response = Http::post(env('ND_API_URL').'/api/Wxpay/huidiao', $data);
//        $last = $response->body();
//        $result = json_decode($last,true);
//        if($result){
//            info('农道回调数据',$result);
//        }
        foreach ($data['sub_orders'] as $item){
            $active_order = ShopOrder::query()->where('status',0)->where('out_trade_no',$item['out_trade_no'])->first();
            if($active_order){
                $active_order->transaction_id = $item['transaction_id'];
                $active_order->status = 1;
                $active_order->pay_type = 4;
                $active_order->save();
            }
            $order = OrderFlow::query()->where('status',0)->where('out_trade_no',$item['out_trade_no'])->first();
            // CapitalFlow::query()->where('order_sn',$order->order_sn)->update(['out_trade_no'=>$item['out_trade_no'],'transaction_id'=>$item['transaction_id']]);
            if($order){

                if($order->commission_rate>0){
                    // 支付成功后 分佣计算
                    //  event(new CommissionEvent($order));
                    // 异步分账功能
                    DevideAccount::dispatch($order)->delay(now()->addMinutes(1));
                }
                $order->status = 1;
                $order->real_price = $item['amount']['total_amount']/100;
                $order->transaction_id = $item['transaction_id'];
                $order->sub_mchid = $item['sub_mchid'];
                $order->save();
                $this->setMchBanlance($order,1);
            }

        }
    }
}
